package mysql

import (
	"gorm.io/gorm"
	"video-system/userrpc/userrpc"
)

type VideoInfo struct {
	gorm.Model
	UploadUserId  int64  `gorm:"type:int(11);not null;comment:'上传用户ID'"`
	VideoTitle    string `gorm:"type:varchar(50);not null;comment:'视频标题'"`
	VideoCategory string `gorm:"type:varchar(50);not null;comment:'视频分类'"`
	VideoLink     string `gorm:"type:varchar(500);not null;comment:'视频URL'"`
	CoverLink     string `gorm:"type:varchar(500);not null;comment:'视频封面'"`
	VideoIntro    string `gorm:"type:varchar(500);comment:'视频简介'"`
	PlayNum       int64  `gorm:"type:int(11);default:0;comment:'播放量'"`
	LikeNum       int64  `gorm:"type:int(11);default:0;comment:'点赞数'"`
	CollectNum    int64  `gorm:"type:int(11);default:0;comment:'收藏数'"`
	CommentNum    int64  `gorm:"type:int(11);default:0;comment:'评论数'"`
	VideoStatus   int64  `gorm:"type:int(11);default:1;comment:'视频状态'"`
	TopicId       int64  `gorm:"type:int(11);comment:'话题ID'"`
	VideoDuration string `gorm:"type:varchar(50);comment:'视频时长'"`
}

func (i *VideoInfo) VideoAdd(db *gorm.DB) error {
	return db.Debug().Create(i).Error
}

func (i *VideoInfo) FindVideoById(db *gorm.DB, id int64) error {
	return db.Debug().Where("id = ?", id).Find(i).Error
}

func (i *VideoInfo) UpdateStatus(db *gorm.DB) error {
	return db.Debug().Updates(i).Error
}

func (i *VideoInfo) VideoDel(db *gorm.DB, id int64) error {
	return db.Debug().Where("id = ?", id).Delete(i).Error
}

func (i *VideoInfo) VideoCount(db *gorm.DB, id int64) userrpc.VideoCountResponse {
	var show userrpc.VideoCountResponse

	db.Debug().Model(&VideoInfo{}).Select("video_infos.*").Where("id = ?", id).First(&show)
	db.Debug().Model(&VideoInfo{}).Where("id = ?", id).Update("play_num", gorm.Expr("play_num+?", 1))
	return show

}

func (i *VideoInfo) CommentVideoShow(db *gorm.DB, id int64) userrpc.CommentListResponse {
	var show userrpc.CommentListResponse
	db.Debug().Model(&VideoInfo{}).Select("video_infos.*,user_infos.nick_name,user_infos.avatar_link").
		Joins("left join user_infos on user_infos.id = video_infos.upload_user_id").Where("video_infos.id = ?", id).First(&show)
	return show

}

func VideoList(db *gorm.DB, in *userrpc.VideoListRequest) []*userrpc.VideoList {
	var list []*userrpc.VideoList

	tx := db.Debug().Model(&VideoInfo{}).Select("video_infos.*").Scopes(Paginate(int(in.Page), int(in.Size)))

	if in.SortType == 0 {
		tx.Order("play_num desc")
	}

	if in.SortType == 1 {
		tx.Order("created_at desc")
	}

	tx.Find(&list)

	return list
}

func VideoShow(db *gorm.DB, id int64) []*userrpc.VideoShow {
	var list []*userrpc.VideoShow

	db.Debug().Model(&VideoInfo{}).Select("video_infos.*,user_infos.nick_name,user_infos.avatar_link,topic_infos.topic_name").
		Joins("left join user_infos on user_infos.id = video_infos.upload_user_id").
		Joins("left join topic_infos on topic_infos.id = video_infos.topic_id").Where("video_infos.upload_user_id = ?", id).
		Order("video_infos.play_num desc").
		Limit(3).
		Find(&list)
	return list

}
